import { getUserInfo, getUserGrade } from '../../utils/userInfo';
import Notify from '@vant/weapp/notify/notify';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userAvatar: '../../images/default-avatar.png', // 用户头像
    desc1: '请选择', // 年级描述1
    desc2: '请选择', // 年级描述2
    showPopup: false, // 弹出层
    mainActiveIndex: 0,
    activeId: null,
    treeItems: Array,
    //轮播图
    swiperCurrent: 1,
    swiperArr: [{
      images: 'https://img1.baidu.com/it/u=720637831,822969472&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500'
    },
    {
      images: 'https://img1.baidu.com/it/u=3203093708,3857840599&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500'
    },
    {
      images: 'https://img2.baidu.com/it/u=3661563575,2356185320&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=281'
    },
    {
      images: 'https://img2.baidu.com/it/u=1267522973,133410182&fm=253&fmt=auto&app=138&f=JPEG?w=670&h=419'
    }
    ],
    indicatorDots: true,
    autoplay: true,
    interval: 2000,
    duration: 1000,
    circular: true,
    beforeColor: "white",//指示点颜色 
    afterColor: "coral",//当前选中的指示点颜色 
    previousmargin: '45rpx',//前边距
    nextmargin: '45rpx',//后边距
  },

  // 轮播图的切换事件 
  swiperChange: function (e) {
    // console.log(e.detail.current);
    this.setData({
      swiperCurrent: e.detail.current //获取当前轮播图片的下标
    })
  },

  /**
  * 点击单个图片进行预览
  */
  onPreviewOneImg: function (event) {
    var src = event.currentTarget.dataset.src;//获取data-src
    const urls = [src];
    //图片预览
    wx.previewImage({
      current: src, // 当前显示图片的http链接
      urls,
    })
  },

  // 滑动图片切换 
  chuangEvent: function (e) {
    this.setData({
      swiperCurrent: e.currentTarget.id
    })
  },

  // 开启弹出层
  onShowPopup() {
    if (getUserInfo()) {
      this.setData({
        showPopup: true
      })
    } else {
      Notify({ type: 'danger', message: '请先登录' });
    }
  },

  // 关闭弹出层
  onClosePopup() {
    this.setData({
      showPopup: false
    })
  },

  // TreeSelect 分类选择器
  // 点击左侧
  onClickNav({ detail = {} }) {
    this.setData({
      mainActiveIndex: detail.index || 0,
    });
    // console.log(this.data.mainActiveIndex);
  },

  // 点击右侧
  onClickItem({ detail = {} }) {
    const activeId = this.data.activeId === detail.id ? null : detail.id;
    this.setData({ activeId });
    // console.log(this.data.activeId);
  },

  // bindTapTreeItems 点击选好了
  bindTapTreeItems() {
    const { mainActiveIndex, activeId, treeItems } = this.data;
    // 将选中的年级分类存入缓存，方便两个页面同步
    const gradeDesc = {
      desc1: treeItems[mainActiveIndex].text,
      desc2: treeItems[mainActiveIndex].children[activeId].text
    }
    wx.setStorageSync('gradeDesc', gradeDesc);
    /* wqb_grade数据库操作，将 desc1 和 desc2 传入数据 
      找到相对应年级下的，class 课程数据，然后再进行渲染
    */
    const { _id } = getUserGrade(); // 获取 gid
    wx.cloud.callFunction({
      name: 'reqGradeAPI',
      data: {
        scene: 'GET_CLASS', // 场景值，必传
        gradeDesc, // 年级描述
        gid: _id,
      },
      complete: res => {
        console.log('callFunction test result: ', res);
        wx.setStorageSync('classArr', res.result)
        this.setData({
          showPopup: false
        }, () => {
          this.onLoad();
        })
      },
    })
  },

  // 点击进行拍照或选择图片，然后携带图片参数，跳转至 imgEntry 页面
  toimgEntryPage() {
    if (getUserInfo()) {
      const gradeDesc = wx.getStorageSync('gradeDesc');
      if (gradeDesc) {
        wx.chooseImage({
          sourceType: ['album', 'camera'],
          success: (res) => {
            //获取图片的临时路径
            const tempFilePath = res.tempFilePaths[0];
            console.log('tempFilePath', tempFilePath);
            wx.navigateTo({
              url: `../../packageA/pages/cropper/cropper?imgSrc=${tempFilePath}`,
            })
          },
        })
      } else {
        Notify({ type: 'warning', message: '请先选择你的年级' });
      };
    } else {
      Notify({ type: 'danger', message: '请先登录' });
    }
  },

  // 点击跳转至 textEntry 页面
  totextEntryPage() {
    if (getUserInfo()) {
      const gradeDesc = wx.getStorageSync('gradeDesc');
      if (gradeDesc) {
        wx.navigateTo({
          url: '../../packageA/pages/textEntry/textEntry',
        })
      } else {
        Notify({ type: 'warning', message: '请先选择你的年级' });
      };
    } else {
      Notify({ type: 'danger', message: '请先登录' });
    }
  },

  // 跳转到今日待复习页面
  toReviewToday() {
    wx.navigateTo({
      url: '../../packageA/pages/reviewToday/reviewToday',
    })
  },

  // 跳转到生成测试页面
  toExamPage() {
    const gradeDesc = wx.getStorageSync('gradeDesc');
    if (getUserInfo()) {
      if (gradeDesc) {
        wx.navigateTo({
          url: '../../packageA/pages/examBefore/examBefore',
        })
      } else {
        // 还未选择年级
        Notify({ type: 'warning', message: '测试要首先选择年级哦' });
      }
    } else {
      // 未登录就请先登录
      Notify({ type: 'danger', message: '请先登录' });
    }
  },

  // 跳转题目总览页面
  toQuestionTotal() {
    if (getUserInfo()) {
      wx.navigateTo({
        url: '../../packageA/pages/questionTotal/questionTotal',
      })
    } else {
      // 未登录就请先登录
      Notify({ type: 'danger', message: '请先登录' });
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const { desc1, desc2 } = wx.getStorageSync('gradeDesc');
    const classArr = wx.getStorageSync('classArr');
    if (desc1 && desc2) {
      this.setData({
        desc1,
        desc2,
      })
    };
    if (classArr) {
      this.setData({
        classArr,
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 获取用户信息
    if (getUserInfo()) {
      const { avatar } = getUserInfo();
      const { grade } = getUserGrade();
      this.setData({
        userAvatar: avatar,
        treeItems: grade,
      });
      this.onLoad();
    } else {
      // 未登录就请先登录
      Notify({ type: 'danger', message: '请先登录' });
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({
      showPopup: false
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})